package dbmanager

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

const (
	BoolValue = iota
	IntValue
	StringValue
)

const (
	BoolValueName = "bool"
	IntValueName = "int"
	StringValueName = "string"
)

type WebConfig struct {
	Id 			int64
	Name 		string
	Commit 		string
	Type 		int 			// 0: bool; 1: int; 2: string
	Value 		string
	Created 	int64
	Updated 	int64
	Status 		int				// 0: 有效；1：无效
}

func (w *WebConfig) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *WebConfig) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WebConfig) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WebConfig) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}

	return nil
}

func init() {
	orm.RegisterModel(new(WebConfig))
}

func (w *WebConfig) Select(offset int, limit int, status int, name string, noNameSet []string) ([]*WebConfig, error) {
	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if name != mysqldb.SelectStrAll {
		qs = qs.Filter("name__istartswith", name)
	}
	if len(noNameSet) > 0 {
		cond := orm.NewCondition().AndNot("name__in", noNameSet)
		qs = qs.SetCond(cond)
	}

	var l []*WebConfig
	if _, err := qs.All(&l); err != nil {
		return nil, err
	}

	return l, nil
}

func (w *WebConfig) Count(status int, name string, noNameSet []string) (int64, error) {
	qs := orm.NewOrm().QueryTable(w)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if name != mysqldb.SelectStrAll {
		qs = qs.Filter("name__istartswith", name)
	}
	if len(noNameSet) > 0 {
		cond := orm.NewCondition().AndNot("name__in", noNameSet)
		qs = qs.SetCond(cond)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}
	return count, nil
}